package com.halixun.d2app.net;

import android.annotation.SuppressLint;
import android.os.Build;

import androidx.annotation.RequiresApi;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;

public class CreateRequestEntity {

//    private static String baseUrl = "http://192.168.0.33";//谢总本地ip

    private static String baseUrl = "http://api.pos.halixun.cn";//c#端ip

//    private static String baseUrl = "http://118.24.60.127";//java端ip

    private static WebRestApi webRestApi;

    /**
     * 决定是否重新创建WebService，true时，重新创建；false时再判断webRestApi==null，为null,重新
     * 创建；不为null,不必重新创建。
     */
    public static boolean isCreateWebService = false;


    public static WebRestApi getWebService() {
        return createRequest();
    }

    private synchronized static WebRestApi createRequest() {
        if (webRestApi == null || isCreateWebService) {
            webRestApi = getRetrofit();
            isCreateWebService = false;
        }
        return webRestApi;
    }

    @SuppressLint("NewApi")
    private static WebRestApi getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getHttpClient())
                .addConverterFactory(FastJsonConverterFactory.create())
                .build().create(WebRestApi.class);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private static OkHttpClient getHttpClient() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        //添加拦截器，自动追加参数
        httpClient.addInterceptor(new AppendUrlParamIntercepter());
        httpClient.addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder request = original.newBuilder();
            request.addHeader("Content-Type","application/json");
            request.addHeader("Connection", "close")
                    .addHeader("Cache-Control", "no-cache");
            return chain.proceed(request.method(original.method(), original.body())
                    .build());
        });
        return httpClient.build();
    }
}
